package com.jsnj33.pdaproject.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.AdjustmentAdapter;
import com.jsnj33.pdaproject.adapter.FormHorizontalAdapter;
import com.jsnj33.pdaproject.base.BaseActivity;
import com.jsnj33.pdaproject.bean.BatchAndProductBean;
import com.jsnj33.pdaproject.bean.MainBean;
import com.jsnj33.pdaproject.bean.MsgBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.SaNetUtils;
import com.jsnj33.pdaproject.utils.SharedpreferencesHelp;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.StringEntity;

public class InventoryActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "InventoryActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action
    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    private Button btnRetryScan;
    private TextView title;
    private EditText etWh;
    private AlertDialog dialog;
    private AdjustmentAdapter adapter;

    private List<BatchAndProductBean> list = new ArrayList<>();
    private List<MainBean> listAdress;
    private String tailUrl;

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            android.util.Log.i("debug", "----codetype--" + temp);
            String str = new String(barcode, 0, barcodelen);
            Log.i(TAG, "onReceive: " + str);
            Log.i(TAG, "onReceive: " + temp);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(InventoryActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);
            switch (sbs) {
                //扫描货品码
                case "ht":
                    setGoodsData(str);
                    break;
                default:
                    etWh.setText(str);
                    break;
            }

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_inventory);
        btnRetryScan = findViewById(R.id.btnRetryScan);

        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();

        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    private void initData() {
        title = findViewById(R.id.title);
        etWh = findViewById(R.id.et_wh);
        RecyclerView rvHorizontal = findViewById(R.id.recyclerview_horizontal);
        RecyclerView rvVertical = (RecyclerView) findViewById(R.id.recyclerview_vertical);
        Button submit = (Button) findViewById(R.id.submit);

        submit.setOnClickListener(this);

        Intent intent = getIntent();
        if (intent != null) {
            title.setText(getIntent().getStringExtra("title"));
            listAdress = (List<MainBean>) getIntent().getSerializableExtra("list");
            tailUrl = listAdress.get(0).getAddress();
        }
        rvHorizontal.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        FormHorizontalAdapter adapterHorizontal = new FormHorizontalAdapter(this) {
            @Override
            protected void itemChick(String address) {
                tailUrl = address;
            }
        };
        rvHorizontal.setAdapter(adapterHorizontal);
        adapterHorizontal.setList(listAdress);


        initRecyclerView(rvVertical, LinearLayoutManager.VERTICAL);
        btnRetryScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeInfo();
            }
        });
    }

    private void initRecyclerView(RecyclerView recyclerView, int vertical) {
        recyclerView.setLayoutManager(new LinearLayoutManager(this, vertical, false));
        adapter = new AdjustmentAdapter(this, false);
        recyclerView.setAdapter(adapter);
    }

    private void fillInData(final int position) {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(InventoryActivity.this);
        View view = LayoutInflater.from(InventoryActivity.this).inflate(R.layout.popup_number_view, null);
        builder.setView(view);
        //这个位置十分重要，只有位于这个位置逻辑才是正确的
        dialog = builder.show();
        dialog.setTitle("请输入:");
        final EditText etNumber = view.findViewById(R.id.et_number);
        view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                list.get(position).setSmqty(Double.parseDouble(etNumber.getText().toString()));
                adapter.setList(list);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit:
                submitData();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * prd_no:扫到的货品码
     * mo_no:制令单号
     * qty:实缴数
     * user：作业人员
     * wh:仓库
     */
    private void submitData() {

        if (StringUtility.isEmpty(etWh.getText().toString())) {
            ToastUtil.showLongGravityToast(InventoryActivity.this, "请填写仓库", Gravity.CENTER, 0, 0);
        }

        if (list.size() <= 0) {
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            list.get(i).setWh(etWh.getText().toString());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("usr", SharedpreferencesHelp.search(InventoryActivity.this, "User", "user"));
        map.put("table", listAdress.get(0).getCodeName());
        map.put("tablename", title.getText().toString());
        map.put("list", list);
        String url = Constants.SUBMIT_ZANGU;
        getHttpData(url, map);
    }

    private void getHttpData(final String url, Map<String, Object> map) {
        AsyncHttpClient client = SaNetUtils.getAsyncHttpClient();
        Log.i(TAG, "getHttpData: " + map.toString());
        try {
            String str = com.alibaba.fastjson.JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue);
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            client.post(this, url, stringEntity, "application/json", new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject) {
                    super.onSuccess(statusCode, headers, jsonObject);
                    Log.i(TAG, "onSuccess: " + jsonObject.toString());
                    try {
                        int errCode = jsonObject.getInt("errCode");
                        String msg = jsonObject.getString("errMsg");
                        if (errCode == -1) {
                            ToastUtil.showLongGravityToast(InventoryActivity.this, msg, Gravity.CENTER, 0, 0);
                        } else {
                            //请求成功
                            removeInfo();
                            ToastUtil.showToast(InventoryActivity.this, "提交成功");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    Log.i(TAG, "onFailure: " + throwable.getMessage());
                    ToastUtil.showGravityToast(InventoryActivity.this, "获取失败!", Gravity.CENTER, 0, 0);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫描制令单号
     *
     * @param osNo
     */
    private void setGoodsData(final String osNo) {
        AsyncHttpClient client = SaNetUtils.getAsyncHttpClient();
        String url = Constants.SCANNING_PRODUCT_CODE + tailUrl;
        final JSONObject map = new JSONObject();
        try {
            map.put("barcode", osNo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            StringEntity stringEntity = new StringEntity(map.toString());
            Log.i(TAG, "setGoodsData: " + stringEntity);
            stringEntity.setContentType("application/json");
            client.post(this, url, stringEntity, "application/json", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    super.onSuccess(statusCode, headers, response);
                    Log.i(TAG, "onSuccess: " + response.toString());
                    String str = new String(response.toString());
                    try {
                        BatchAndProductBean beans = new Gson().fromJson(str, BatchAndProductBean.class);

                        if (list.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                BatchAndProductBean batchAndProductBean = list.get(i);
                                if (batchAndProductBean.getPrd_no().equals(beans.getPrd_no())
                                        && batchAndProductBean.getBat_no().equals(beans.getBat_no())) {
                                    fillInData(i);
                                    return;
                                }
                            }
                        }

                        list.add(0, beans);
                        adapter.setList(list);
                        fillInData(0);


                    } catch (Exception e) {
                        Log.i(TAG, "onSuccess: " + e.getMessage());
                        try {
                            List<MsgBean> msgBean = new Gson().fromJson(str, new TypeToken<List<MsgBean>>() {
                            }.getType());
                            MsgBean bean = msgBean.get(0);
                            int errCode = bean.getErrCode();
                            String msg = bean.getErrMsg();
                            if (errCode == -1) {
                                ToastUtil.showLongGravityToast(InventoryActivity.this, msg, Gravity.CENTER, 0, 0);
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    super.onSuccess(statusCode, headers, responseString);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray jsonObject) {
                    super.onSuccess(statusCode, headers, jsonObject);
                    String str = new String(jsonObject.toString());
                    Log.i(TAG, "onSuccess: " + jsonObject.toString());
                    try {
                        BatchAndProductBean beans = new Gson().fromJson(str, BatchAndProductBean.class);

                        if (list.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                BatchAndProductBean batchAndProductBean = list.get(i);
                                if (batchAndProductBean.getPrd_no().equals(beans.getPrd_no())
                                        && batchAndProductBean.getBat_no().equals(beans.getBat_no())) {
                                    fillInData(i);
                                    return;
                                }
                            }
                        }

                        list.add(0, beans);
                        adapter.setList(list);
                        fillInData(0);


                    } catch (Exception e) {
                        try {
                            List<MsgBean> msgBean = new Gson().fromJson(str, new TypeToken<List<MsgBean>>() {
                            }.getType());
                            MsgBean bean = msgBean.get(0);
                            int errCode = bean.getErrCode();
                            String msg = bean.getErrMsg();
                            if (errCode == -1) {
                                ToastUtil.showLongGravityToast(InventoryActivity.this, msg, Gravity.CENTER, 0, 0);
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    Log.i(TAG, "onFailure: " + throwable.getMessage());
                    ToastUtil.showGravityToast(InventoryActivity.this, "获取失败!", Gravity.CENTER, 0, 0);
                }

            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交数据后清空数据
     */
    private void removeInfo() {
        if (list != null) {
            list.clear();
        }
        etWh.setText("");
        adapter.setList(list);
    }

}
